package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Middleware(c *gin.Context) {
	fmt.Println("This is a middleware!")
}

func GetHandler(c *gin.Context) {
	value, exist := c.GetQuery("key")
	if !exist {
		value = "the key is not exist!"
	}

	c.Data(http.StatusOK, "text/plain", []byte(fmt.Sprintf("get success! %s\n", value)))
}

func PostHandler(c *gin.Context) {
	type JsonHolder struct {
		Id   int    `json:"id"`
		Name string `json:"name"`
	}
	holder := JsonHolder{Id: 1, Name: "andy"}

	c.JSON(http.StatusOK, holder)
}

func PutHandler(c *gin.Context) {
	c.Data(http.StatusOK, "text/plain", []byte("put success!\n"))
}

func DeleteHandler(c *gin.Context) {
	c.Data(http.StatusOK, "text/plain", []byte("delete success!\n"))
}

func upload(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["upload[]"]

	for _, file := range files {
		fmt.Println(file.Filename)
		err := c.SaveUploadedFile(file, fmt.Sprintf("temp/%s", file.Filename))
		if err != nil {
			fmt.Println("upload file:" + file.Filename + " " + err.Error())
		}
	}
	c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
}

func main() {
	gin.SetMode(gin.DebugMode)
	router := gin.Default()

	// Add middleware
	router.Use(Middleware)

	// register the API
	router.GET("/simple/server/get", GetHandler)
	router.POST("/simple/server/post", PostHandler)
	router.PUT("/simple/server/put", PutHandler)
	router.DELETE("/simple/server/delete", DeleteHandler)

	router.POST("simple/server/upload", upload)

	//listen the port
	http.ListenAndServe(":8005", router)
}
